# core/dwg_processor.py
import win32com.client
import pythoncom
import os


class DWGProcessor:
    def __init__(self):
        self.inventor = None
        self._init_inventor()

    def _init_inventor(self):
        """启动Inventor实例"""
        try:
            self.inventor = win32com.client.Dispatch("Inventor.Application")
            self.inventor.Visible = True
        except Exception as e:
            raise RuntimeError(f"Inventor启动失败: {str(e)}")

    def process_dwg(self, dwg_path: str):
        """处理DWG文件生成三维模型"""
        if not os.path.exists(dwg_path):
            raise FileNotFoundError(f"DWG文件不存在: {dwg_path}")

        try:
            # 创建新零件文档
            part_doc = self.inventor.Documents.Add(12289)  # 12289=kPartDocumentObject

            # 导入DWG草图
            translator = self.inventor.Application.TranslatorManager
            options = translator.GetDWGFileOpenOptions()
            options.FileOpenOptions.PromoteSketches = True

            # 执行导入
            translator.ImportToFile2(
                dwg_path,
                part_doc.FullFileName,
                options
            )

            return part_doc
        except Exception as e:
            self.inventor.Quit()
            raise RuntimeError(f"DWG导入失败: {str(e)}")


# 使用示例
processor = DWGProcessor()
model = processor.process_dwg("C:/designs/drawing.dwg")